using Microsoft.EntityFrameworkCore;
using TerritoryGame.Domain.Repositories;
using TerritoryGame.Infrastructure.Data;

namespace TerritoryGame.Infrastructure.Repositories;

/// <summary>
/// Entity Framework Core 通用仓储实现
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
public class EfRepository<T> : IRepository<T> where T : class
{
    protected readonly TerritoryGameDbContext _context;
    protected readonly DbSet<T> _dbSet;

    public EfRepository(TerritoryGameDbContext context)
    {
        _context = context;
        _dbSet = context.Set<T>();
    }

    public virtual async Task<T?> GetByIdAsync(Guid id)
    {
        return await _dbSet.FindAsync(id);
    }

    public virtual async Task<IEnumerable<T>> GetAllAsync()
    {
        return await _dbSet.ToListAsync();
    }

    public virtual async Task<T> CreateAsync(T entity)
    {
        var entry = await _dbSet.AddAsync(entity);
        await _context.SaveChangesAsync();
        return entry.Entity;
    }

    public virtual async Task<T> UpdateAsync(T entity)
    {
        var entry = _dbSet.Update(entity);
        await _context.SaveChangesAsync();
        return entry.Entity;
    }

    public virtual async Task DeleteAsync(Guid id)
    {
        var entity = await GetByIdAsync(id);
        if (entity != null)
        {
            _dbSet.Remove(entity);
            await _context.SaveChangesAsync();
        }
    }
}
